import os

from dev_tools.slpp import slpp
from module.logger import logger  # Change folder automatically


def load_lua(folder, file, prefix):
    with open(os.path.join(folder, file), 'r', encoding='utf-8') as f:
        text = f.read()
    print('Loading technology_data_template')
    result = slpp.decode(text[prefix:])
    print(f'{len(result.keys())} items loaded')
    return result


class Item:
    def __init__(self, data):
        """
        Args:
            data (dict): Such as {0: 2, 1: 20001, 2: 5}
        """
        self.name = ''
        _, self.id, self.amount = data.values()
        if self.id == 1:
            self.id = 59001  # The id of coins is 1 in technology_data_template, but 59001 in item_data_statistics

    def __str__(self):
        return f'{self.name}({self.id}) x {self.amount}'


class Task:
    def __init__(self, data):
        self.name = ''
        self.id = data


class Project:
    def __init__(self, data):
        """
        Args:
            data (dict):
        """
        self.name = data['name']
        self.series = int(data['blueprint_version'])
        self.time = int(data['time'])
        self.input = [Item(item) for item in data['consume'].values()]
        self.output = [Item(item) for item in data['drop_client'].values()]
        self.task = Task(int(data['condition']))

    def encode(self):
        data = {
            'name': self.name,
            'series': self.series,
            'time': self.time,
            'task': self.task.name,
            'input': [{'name': item.name, 'amount': item.amount} for item in self.input],
            'output': [{'name': item.name} for item in self.output],
        }
        return str(data)


class TechnologyTemplate:
    def __init__(self, folder):
        tech = load_lua(folder, 'technology_data_template.lua', prefix=44)
        item = load_lua(folder, 'item_data_statistics.lua', prefix=40)
        task = load_lua(folder, 'task_data_template.lua', prefix=38)

        self.projects = []
        for key, value in tech.items():
            if key == 'all':
                continue
            project = Project(value)
            if project.task.id:
                project.task.name = task[project.task.id]['desc'].replace('\\n', '')
            for i in project.input:
                i.name = item[i.id]['name'].strip()
            for i in project.output:
                i.name = item[i.id]['name'].strip()

            self.projects.append(project)

    def encode(self):
        lines = []
        lines.append('# This file is generated by dev_tools.research_extractor.')
        lines.append("# Don't modified it manually.")
        lines.append('')
        lines.append('LIST_RESEARCH_PROJECT = [')
        for project in self.projects:
            lines.append('    ' + project.encode() + ',')
        lines.append(']')

        return lines

    def write(self, file):
        print(f'writing {file}')
        with open(file, 'w', encoding='utf-8') as f:
            for text in self.encode():
                f.write(text + '\n')


"""
This an auto-tool to extract research projects used in Alas.

Git clone https://github.com/Dimbreath/AzurLaneData, to get the decrypted scripts.
Arguments:
    FILE:  Path to sharecfg, '<your_folder>/<server>/sharecfg'
    SAVE:  File to save, 'module/research/project_data.py'
"""
FOLDER = ''
SAVE = 'module/research/project_data.py'

tt = TechnologyTemplate(FOLDER)
tt.write(SAVE)
